package cn.haoxsf.app.system.controller;


import cn.haoxsf.app.common.api.CommonResult;
import cn.haoxsf.app.common.api.enums.SystemExceptionEnum;
import cn.haoxsf.app.common.apo.repeat.Submit;
import cn.haoxsf.app.common.pojo.PageFactory;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.system.entity.Cost;
import cn.haoxsf.app.system.entity.FaultCategory;
import cn.haoxsf.app.system.entity.FaultItem;
import cn.haoxsf.app.system.entity.Order;
import cn.haoxsf.app.system.model.param.OrderParam;
import cn.haoxsf.app.system.model.param.OrderRelationParam;
import cn.haoxsf.app.system.model.vo.ResultPage;
import cn.haoxsf.app.system.service.ICostService;
import cn.haoxsf.app.system.service.IFaultCategoryService;
import cn.haoxsf.app.system.service.IFaultItemService;
import cn.haoxsf.app.system.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ele  qvbanfm@qq.com
 * @since 2020-03-17
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单相关请求")
public class OrderController {
    @Autowired
    private IOrderService orderService;//订单
    @Autowired
    private ICostService costService;//费用
    @Autowired
    private IFaultItemService faultItemService;//故障详情
    @Autowired
    private IFaultCategoryService faultCategoryService;//故障类目


    @PostMapping("create")
    @ApiOperation("用户创建订单")
    @Submit
    public CommonResult createOrder(@ApiParam @RequestBody @Validated OrderParam param, BindingResult result) {
        //创建订单
        if (result.hasErrors()) {
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED.getCode(), result.getFieldError().getDefaultMessage());
        }
        if (ToolUtil.isNotEmpty(param.getBusinessId())) {
            return CommonResult.error(SystemExceptionEnum.SERVER_ERROR.getCode(), "正在开发，敬请期待");
        }
        orderService.create(param);
        return CommonResult.success();
    }

    @ApiOperation("获取费用和故障类别-AIR_CONDITIONER-APPLIANCE-CAR 目前只开启了TRAM（电车修）")
    @GetMapping("getCost")
    public CommonResult getCost(@ApiParam(value = "AIR_CONDITIONER-APPLIANCE-CAR 目前只开启了TRAM（电车修）", example = "TRAM") @RequestParam String category) {
        FaultCategory faultCategoryByCategoryCode = faultCategoryService.getFaultCategoryByCategoryCode(category);//类目
        Cost one = costService.getOne(new QueryWrapper<Cost>().eq("cost_name", faultCategoryByCategoryCode.getCategoryCode()));//费用
        List<FaultItem> list = faultItemService.list();//故障类型
        Map<String, Object> map = new HashMap<>();
        if (ToolUtil.isEmpty(one)) {
            return CommonResult.error(SystemExceptionEnum.NOT_DATA);
        }
        if (ToolUtil.isEmpty(list)) {
            return CommonResult.error(SystemExceptionEnum.NOT_DATA);
        }
        map.put("cost", one);
        map.put("faultList", list);
        map.put("category", faultCategoryByCategoryCode);
        return CommonResult.success(map);
    }

    @ApiOperation(value = "取消订单/关闭订单", notes = "注意订单如果是orderStatus = PAID 已支付状态无法取消")
    @PostMapping("cancel")
    @Submit
    public CommonResult cancel(@RequestParam(required = false) String orderNo) {
        if (ToolUtil.isEmpty(orderNo)) {
            return CommonResult.error(SystemExceptionEnum.VALIDATE_FAILED.getCode(), "orderNo不能为空");
        }
        Boolean cancel = orderService.cancel(orderNo);
        if (cancel) {
            return CommonResult.success();
        } else {
            return CommonResult.error(SystemExceptionEnum.FAILED);
        }
    }

    @ApiOperation(value = "获取订单- 注意查询订单是当前登陆的用户发布的订单集合", notes = "注意查询订单是当前登陆的用户的订单")
    @PostMapping("list")
    public CommonResult getList(@ApiParam("分页参数") @RequestBody PageFactory page) {
        Page<Order> myPage = new Page<>(page.getPage(), page.getLimit());
        //option 选项 为get 查询发订单,All为查询全都订单 B为查询接的订单
        List<Map<String, Object>> myOrderPage = orderService.getMyOrderPage(myPage, page.getMode(), page.getLat(), page.getLng(), page.getMe());
        ResultPage<Map<String, Object>> mapResultPage = new ResultPage<>(myPage.getSize(), myPage.getCurrent(), myPage.getTotal(), myOrderPage);
        return CommonResult.success(mapResultPage);
    }

    @ApiOperation(value = "下单接口,注意是要师傅(商户)权限", notes = "注意是要师傅(商户)权限")
    @PreAuthorize("hasAuthority('xsf:bus:yes')")
    @Submit
    @PostMapping("receipt")
    public CommonResult receipt(@ApiParam("下单参数") @RequestBody OrderRelationParam param) {
        Order receipt = orderService.receipt(param.getOrderId());
        return CommonResult.success(receipt);
    }

    @ApiOperation(value = "用于查询接到的订单,注意是要师傅(商户)权限,mode不用传参数 按默认就可以了")
    @Submit
    @PostMapping("toOrder")
    @PreAuthorize("hasAuthority('xsf:bus:yes')")
    public CommonResult GetToOrder(@ApiParam("分页参数") @RequestBody PageFactory page) {
        Page<Order> myPage = new Page<>(page.getPage(), page.getLimit());
        List<Map<String, Object>> myOrderPage = orderService.getMyOrderPage(myPage, "B", page.getLat(), page.getLng(), page.getMe());
        if (ToolUtil.isEmpty(myOrderPage)) {
            return CommonResult.error(SystemExceptionEnum.NOT_DATA);
        }
        ResultPage<Map<String, Object>> mapResultPage = new ResultPage<>(myPage.getSize(), myPage.getCurrent(), myPage.getTotal(), myOrderPage);
        return CommonResult.success(mapResultPage);
    }


    @ApiOperation(value = "用于完成任务，注意是要师傅(商户)权限")
    @Submit
    @PostMapping("complete-order")
    @PreAuthorize("hasAuthority('xsf:bus:yes')")
    public CommonResult completeOrder(@RequestParam String orderNo) {
        orderService.completeOrder(orderNo);
        return CommonResult.success();
    }
}
